package mysqlConn

import (
	"beego_base_demo/JsonCfg"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"sync"
)
var lock sync.Mutex
type error interface {
	Error() string
}
type mysqlCfg struct {
	Host string `json:"host"`
	Port string `json:"port"`
	User string `json:"user"`
	Passwd string `json:"passwd"`
	Dbname string `json:"dbname"`
}
var instance *gorm.DB
func init() {
	instance=initdb("mysqlCfg.json")
}
func initdb(cfgname string) *gorm.DB  {
	var cfg mysqlCfg
	ok:= JsonCfg.LoadCfg(&cfg,"cfg\\"+cfgname)
	if ok != true {
		fmt.Println("loadcfg failed")
		return nil
	}
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", cfg.User, cfg.Passwd, cfg.Host, cfg.Port, cfg.Dbname )
	fmt.Println(cfg)
	tdb, err := gorm.Open("mysql",dsn)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	fmt.Println("Load mysql success")
	tdb.LogMode(true)
	return tdb
}


func GetInstance() *gorm.DB {
	lock.Lock()
	defer lock.Unlock()
	return instance
}


func NewRecord(value interface{})  {
	fmt.Println(instance.NewRecord(value))
}
func CreateTable(value interface{})  {
	if !instance.HasTable(value){
		fmt.Println(instance.CreateTable(value))
	}
}
func Create(value interface{})  {
	fmt.Println(instance.Create(&value))
}
